﻿/*
 *  PassBag is multi-platform software that securely manage/store passwords
 *  Copyright (C) <2009>  <Hugo Rodrigues PEREIRA>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *	
 *  You can find a copy of the GPLv3 at project <root directory>/gpl.txt
 *
 */ 
 
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace PassBag.Data {

    /// <summary>
    /// Serialize and deserialize a generic list to a XML file
    /// </summary>
    public class ObjectSerializer {      
        /// <summary>
        /// Serialize an object into an XML file
        /// </summary>
        /// <param name="filename">XML file name</param>
        /// <param name="obj">Object to serialize</param>
        /// <returns>Return true if serialize successfull</returns>
        public static bool SerializeObject<T> (string filename, T obj) {
            try {
                XmlSerializer xs = new XmlSerializer (typeof (T));
                TextWriter xmlTextWriter = new StreamWriter(filename, false, Encoding.UTF8);
                xs.Serialize (xmlTextWriter, obj);
                xmlTextWriter.Close ();

                return true;
            }
            catch  {
                return false;
            }
        }

        /// <summary>
        /// Deserialize an object from an XML file
        /// </summary>
        /// <param name="filename">XML file name</param>
        /// <returns>The deserialized object</returns>
        public static T DeserializeObject <T>(string filename) {
            T t;
            XmlSerializer serializer = new XmlSerializer (typeof (T));
            using (TextReader tr = new StreamReader (filename, Encoding.UTF8)) {
                t = (T)serializer.Deserialize (tr);
                tr.Close ();
            }
            return t;
        }
    }
}
